//
//  UILabel + Extra.m
//  Voxper
//
//  Created by Erphan on 2/17/11.
//  Copyright 2011 Smonte. All rights reserved.
//

#import "UILabel + Extra.h"

@implementation CopyPasteLabel

#pragma mark Initialization

- (void) attachTapHandler
{
    [self setUserInteractionEnabled:YES];
    UIGestureRecognizer *touchy = [[UITapGestureRecognizer alloc]
								   initWithTarget:self action:@selector(handleTap:)];
    [self addGestureRecognizer:touchy];
    [touchy release];
}

- (id) initWithFrame: (CGRect) frame
{
    [super initWithFrame:frame];
    [self attachTapHandler];
    return self;
}

- (void) awakeFromNib
{
    [super awakeFromNib];
    [self attachTapHandler];
}

#pragma mark Clipboard

- (void)copy: (id)sender {
	if ([self.text length] == 0) {
		return;
	}
	
	UIPasteboard *appPasteBoard = [UIPasteboard generalPasteboard];
	appPasteBoard.persistent = YES;
	[appPasteBoard setString:self.text];
}

- (void)paste:(id)sender {
	UIPasteboard *appPasteBoard = [UIPasteboard generalPasteboard];
	NSString *temp = [appPasteBoard string];
	if (temp) {
		self.text = temp;
	}
}

- (BOOL) canPerformAction: (SEL) action withSender: (id) sender
{
    if(action == @selector(copy:)) {
		return YES;
	} else if(action == @selector(paste:)) {
		return YES;
	} else {
		return [super canPerformAction:action withSender:sender];
	}
}

- (void) handleTap: (UIGestureRecognizer*) recognizer
{
    [self becomeFirstResponder];
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setTargetRect:self.frame inView:self.superview];
    [menu setMenuVisible:YES animated:YES];
}

- (BOOL) canBecomeFirstResponder
{
    return YES;
}

@end